package heima_bixiangdong.pro_con;

import java.util.concurrent.TimeUnit;

public class WaitAndNotify {
    public static void main(String[] args) {
        test1();
    }

    private static void test1() {
        final Object lock = new Object();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程A等待获得锁");
                synchronized (lock){
                    try{
                        System.out.println("线程A获得锁");
                        TimeUnit.SECONDS.sleep(1);
                        System.out.println("线程A开始执行wait()");
                        lock.wait();
                        System.out.println("线程A结束执行wait()");
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        },"Thread-A").start();

        new Thread(new Runnable(){
            @Override
            public void run() {
                System.out.println("线程B等待获得锁");
                synchronized (lock){
                    System.out.println("线程B获得锁");
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    lock.notify();
                    System.out.println("线程B执行notify()");
                }
            }
        }).start();
    }
}
